/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-08
 * Time: 9:35
 */
public class MyBlockingQueue {
    public int[] data;
    private volatile int size = 0;//当前元素个数
    private volatile int tail = 0;//队尾
    private volatile int head = 0;//队头

    public MyBlockingQueue(int n) {
        data = new int[n];
    }

    public void put(int val) throws InterruptedException {
        synchronized (this) {
            while (size >= data.length) {
                //满了,阻塞
                this.wait();
            }
            data[size] = val;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    public int take() throws InterruptedException {

        int ret;
        synchronized (this) {
            while (size == 0) {
                //队列是空的,阻塞
                this.wait();
            }
            size--;
            ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }
            this.notify();
        }
        return ret;
    }
}
